package com.nervenets.shopping.controller.user.dto;

import com.nervenets.general.enumeration.Platform;
import com.nervenets.general.exception.LogicException;
import com.nervenets.general.model.GeneralModel;
import com.nervenets.general.model.SecurityUser;
import com.nervenets.general.service.GlobalSecurityService;
import com.nervenets.general.utils.JodaUtils;
import com.nervenets.shopping.enumeration.UserType;
import com.nervenets.shopping.hibernate.domain.user.User;
import io.swagger.annotations.ApiModelProperty;
import lombok.*;
import lombok.experimental.SuperBuilder;
import org.springframework.beans.BeanUtils;

@EqualsAndHashCode(callSuper = true)
@Setter
@Getter
@AllArgsConstructor
@NoArgsConstructor
@SuperBuilder
public class UserLoginDto extends GeneralModel {
    @ApiModelProperty(value = "账号")
    private String mobile;
    @ApiModelProperty(value = "昵称")
    private String name;
    @ApiModelProperty(value = "头像")
    private String avatar;
    @ApiModelProperty(value = "密钥")
    private String token;
    @ApiModelProperty(value = "是否启用")
    private boolean enable;
    @ApiModelProperty(value = "是否是推广者")
    private boolean inviter;
    @ApiModelProperty(value = "最后登录时间")
    private long lastLoginTime;
    @ApiModelProperty(value = "最后拼团时间")
    private long lastGroupTime;
    @ApiModelProperty(value = "拼团次数")
    private long groupCount;
    @ApiModelProperty(value = "小程序码图片地址")
    private String shareQrFile;

    public UserLoginDto(User user, boolean newToken, String license, GlobalSecurityService globalSecurityService, LoginInfoVo loginInfo) {
        Platform platform;
        try {
            platform = Platform.valueOf(loginInfo.getPlatformValue());
        } catch (Exception e) {
            throw new LogicException("头文件中user-platform不合法");
        }
        if (Platform.management.equals(platform)) {
            throw new LogicException("user platform not support.");
        }

        BeanUtils.copyProperties(user, this, "token");

        SecurityUser securityUser = new SecurityUser(getId(), user.getMobile(), user.getName());
        securityUser.addExtra("ip", loginInfo.getIp());
        securityUser.addExtra("agent", loginInfo.getUserAgent());
        securityUser.addExtra("userType", UserType.user.name());
        securityUser.addExtra("loginTime", JodaUtils.getTimestamp());
        securityUser.addExtra("platform", loginInfo.getPlatformValue());

        this.token = newToken ? globalSecurityService.getToken(securityUser, license) : null;
    }
}
